package com.zunipe.ftpe.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

public class ZI18n {
    public static final String TAG = "ZI18n";

    private static final Gson gson = new Gson();
    private static final JsonObject jsonObject;

    static {
        String id = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
        StringBuilder s = new StringBuilder();
        byte[] buffer = new byte[1024];
        InputStream is;
        do {
            is = ZI18n.class.getClassLoader().getResourceAsStream(id + ".json");
            if (is == null) {
                id = "en_US";
                continue;
            }
            try {
                int len;
                while ((len = is.read(buffer)) > 0) {
                    s.append(new String(buffer, 0, len));
                }
            } catch (IOException e) {
                ZLog.e(TAG, e.toString());
            } finally {
                try {
                    is.close();
                } catch (IOException ignored) {

                }
            }
        } while (is == null);

        jsonObject = gson.fromJson(s.toString(), JsonObject.class);
    }

    public static String getString(String key) {
        if (jsonObject == null || !jsonObject.has(key)) {
            return key;
        }
        return jsonObject.get(key).getAsString();
    }
}
